/**
 * Created by zhengxw on 2015/10/26.
 * extend mini
 * miniui hack
 * datagrid.load()接口调用时，会把yyyy-MM-dd HH:mm:ss和yyyy-MM-ddTHH:mm:ss两种格式自动转换为Date
 */
mini.decode = function(json) {
    var re = /[\"\'](\d{4})-(\d{1,2})-(\d{1,2})[T](\d{1,2}):(\d{1,2}):(\d{1,2})(\.*\d*)[\"\']/g;
    json = json.replace(re, "new Date($1,$2-1,$3,$4,$5,$6)");
    return eval('(' + json + ')');
};
mini.ComboBox.prototype.reload = mini.ComboBox.prototype.reload || function() {
    if (this.getUrl())
        this.setUrl(this.getUrl());
};
mini.DataGrid.prototype.redraw = mini.ComboBox.prototype.redraw || function() {
    if (this.data)
        this.setData(this.data);
};
mini.DataGrid.prototype.loadJson = mini.ComboBox.prototype.loadJson || function(data) {
    if (typeof data === 'string')
        data = JSON.parse(data);
    if (data) {
        if (data.fields && data.records) {
            var fields = data.fields;
            var columns = [{
                header: '序号',
                headerAlign: 'center',
                type: 'indexcolumn'
            }];
            for (var i = 0, len = fields.length; i < len; i++) {
                field = fields[i];
                columns.push({
                    field: field,
                    name: field,
                    header: field,
                    headerAlign: 'center'
                });
            }
            this.setColumns(columns);
            this.setData(data.records);
            return true;
        } else {
            this.setColumns([]);
            this.setData([]);
        }
    }
    return false;
};
mini.TextBox.prototype.clear = mini.TextBox.prototype.clear || function() {
    this.setValue('');
};
mini.TextArea.prototype.clear = mini.TextArea.prototype.clear || function() {
    this.setValue('');
};
mini.ComboBox.prototype.clear = mini.ComboBox.prototype.clear || function() {
    this.setValue('');
};
mini.DatePicker.prototype.clear = mini.DatePicker.prototype.clear || function() {
    this.setValue('');
};
mini.ButtonEdit.prototype.clear = mini.ButtonEdit.prototype.clear || function() {
    this.setText('');
    this.setValue('');
};
/**-----------------扩展JScript String字符串函数删除字符串左右空格函数-------------*/
if (!String.prototype.trim) {
    String.prototype.trim = function() {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    };
}

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString, position) {
        position = position || 0;
        return this.substr(position, searchString.length) === searchString;
    };
}
/**-------------------js 字符串格式化函数---------------------------------
 * 示例1:
 * var str = "你好{0}";
 * var str1 = "你好{name}"
 * str.format("helloworld");
 * str1.format({name:"helloworld"});
 */
String.prototype.format = function(args) {
    try {
        if (arguments.length > 0) {
            var result = this;
            if (arguments.length == 1 && typeof(args) == "object") {
                for (var key in args) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            } else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] == undefined) {
                        return "";
                    } else {
                        var reg = new RegExp("({[" + i + "]})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
            return result;
        } else return this;
    } catch (e) {
        console.log(e);
    }
};
/** * 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * 
eg: 
* (new Date()).format("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423      
* (new Date()).format("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04      
* (new Date()).format("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04      
* (new Date()).format("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04      
* (new Date()).format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
*/
Date.prototype.format = function(fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份         
        "d+": this.getDate(), //日         
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时         
        "H+": this.getHours(), //小时         
        "m+": this.getMinutes(), //分         
        "s+": this.getSeconds(), //秒         
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度         
        "S": this.getMilliseconds() //毫秒         
    };
    var week = {
        "0": "日",
        "1": "一",
        "2": "二",
        "3": "三",
        "4": "四",
        "5": "五",
        "6": "六"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};
//初始化dataGrid
/*
 * 参数说明：1、dataGrid:页面的列表对象
 */
function initdataGrid(dataGrid, urlvalue) {
    dataGrid.set({
        style: "width:100%;height:100%;",
        allowAlternating: true,
        // 显示斑马纹
        showLoading: true,
        // 显示Loading遮罩效果
        selectOnLoad: true,
        // 加载完是否自动选中
        sizeList: [20, 30, 50, 100],
        showLoading: "true",
        url: urlvalue
    });
    dataGrid.load();
}
// 初始化window格式
/*
 * 参数说明：1、window:页面的window对象 2、width：设置window的宽度 3、height:设置window的高度
 * 4、toolbar：window的toolbar对象
 */
function initWindow(window, width, height, option) {
    window.set({
        style: "width:" + width + "px;height:" + height + "px",
        showModal: (option === void 0 || option.showModal === void 0) ? true : option.showModal,
        allowResize: (option === void 0 || option.allowResize === void 0) ? true : option.allowResize,
        showCloseButton: (option === void 0 || option.showCloseButton === void 0) ? true : option.showCloseButton,
        showMaxButton: (option === void 0 || option.showMaxButton === void 0) ? false : option.showMaxButton,
        showFooter: (option === void 0 || option.showFooter === void 0) ? true : option.showFooter,
        allowDrag: (option === void 0 || option.allowDrag === void 0) ? true : option.allowDrag,
        headerStyle: "height:25px;font-size: 14px;"
    });
}
// 初始化引入的html的格式
/*
 * 参数说明：1、urlHtml:引入的的html的url 2、title：打开的html的标题 3、width：引入到主页面时子页面的宽度
 * 4、height：引入到主页面时子页面的高度
 */
function initHtml(urlHtml, title, width, height, onload, ondestroy) {
    mini.open({
        url: urlHtml,
        title: title,
        width: width,
        height: height,
        onload: function() {
            onload;
        },
        ondestroy: function(action) {
            ondestroy;
        }
    });
}
/**--------------------公共函数-Window编辑窗体确认和取消-----------------
 *关闭打开的window窗体
 * 参数说明：1、window：需要关闭的window对象
 */
function cancel(window) {
    window.hide();
}
// ----------------------html编辑窗体确认和取消-------------------------*/
// 关闭html窗体
function CloseWindow(action) {
    if (window.CloseOwnerWindow) return window.CloseOwnerWindow(action);
    else window.close();
}
// 确认操作关闭窗体
function onOk() {
    CloseWindow("ok");
}
// 取消操作关闭窗体
function onCancel() {
    CloseWindow("cancel");
}
// --------------显影提示框-----------------------
// 显影提示框
function showTips(state, contentText) {
    mini.showTips({
        content: contentText,
        state: state,
        x: 'center',
        y: 'center',
        timeout: 3000
    });
}
// 成功显影提示框
function showSuccessTips(content) {
    showTips('success', content);
}
// 提示显影提示框
function showInfoTips(content) {
    showTips('info', content);
}
// 警告显影提示框
function showWarningTips(content) {
    showTips('warning', content);
}
// 危险显影提示框
function showDangerTips(content) {
    showTips('danger', content);
}
// 根据传入参数弹出显示一个子窗体
function showWindow(win, width, height, title, form, option) {
    if (win) {
        initWindow(win, width, height, option);
        if (title) win.setTitle(title);
        if (form) form.reset();
        win.show();
        clrErrorText(); // 清除提示错误信息
    }
}
// ---------公共：打印格式设置、列表栏目设置、查看功能变量、查看功能参数、查看模块信息、查看记录修改日志---------
/*
 * 参数说明:1、mkxxData：模块信息数据
 */
function showmkxx(mkxxData) {
    mini.open({
        url: 'public/mkxx.html',
        title: "模块信息",
        width: "500",
        height: "400",
        onload: function() {
            var iframe = this.getIFrameEl();
            iframe.contentWindow.setData(mkxxData);
        }
    });
}
// 查看功能参数
/*
 * 参数说明：gncsList:参数列表
 */
function showgncs(gncsList) {
    mini.open({
        url: 'public/gncs.html',
        title: "功能参数显示",
        width: "600",
        height: "400",
        modal: 'yes',
        onload: function() {
            var iframe = this.getIFrameEl();
            iframe.contentWindow.SetData(gncsList);
        }
    });
}
// 查看记录修改日志
function showxgrz() {
    mini.open({
        url: 'public/xgrz.html',
        title: "数据修改日志",
        width: "650",
        height: "400",
        // modal:'yes',
        onload: function() {
            var iframe = this.getIFrameEl();
            iframe.contentWindow.SetData();
        }
    });
}
// 将下拉列表绑定至字典
/*
 * @param param {type: 查询类型 1：简单字典 2：主从字典 dicttype: 字典类型 99:表示查询全部字典 dictvalue:
 * 字典值 mainvalue: 主从字典主键 }
 */
function BindSelect(ctrlName, param) {
    var control = $('#' + ctrlName);
    // 绑定Ajax的内容
    $.post("../getdict.do", param, function(data) {
        control.empty(); // 清空下拉框
        if (data.ret_code == '0000') {
            var type = param.type;
            $.each(data.result, function(i, item) {
                switch (type) {
                    case '1':
                        control.append("<option value='" + item.value + "'>&nbsp;" + item.valuedesc + "</option>");
                        break;
                    case '2':
                        control.append("<option value='" + item.subvalue + "'>&nbsp;" + item.subdesc + "</option>");
                        break;
                }
            });
        }
    });
};
// 页面校验公共函数
function updateError(e) {
    var id = e.sender.name + "_error";
    var el = document.getElementById(id);
    if (el) {
        el.innerHTML = e.errorText;
    }
}
// 清除输入框错误提示信息函数
function clrErrorText() {
    $(".errorText").each(function() {
        $(this).html('');
    });
}
/**
 * 此处开始进行js模块化编写公共js文件
 *
 */
'use strict';
var rs = (function(rs) {
    /**
     * 查询字典配置信息
     *
     * @param param
     *            {type: 查询类型 1：简单字典 2：主从字典 dicttype: 字典类型 99:表示查询全部字典
     *            dictvalue: 字典值 mainvalue: 主从字典主键 }
     */
    rs.qryDictInfo = function(param) {
        return this.getParam("getdict.do", param);
    };
    rs.setGridStyle = function() { // 设置数据列表显示风格
        var dbgridlist = rs.getByType("datagrid");
        dbgridlist.forEach(function(grid) {
            grid.set({
                showColumnsMenu: true,
                // 显示列菜单
                allowAlternating: true,
                // 行之间显示斑马纹
                editNextOnEnterKey: true,
                // 按回车键进入同行下一单元格
                showLoading: true,
                // 显示加载遮罩
                selectOnLoad: true,
                // 加载完自动选中
                allowResizeColumn: true,
                // 允许调整列宽
                sizeList: [20, 30, 50, 100],
                // 设置每页记录数
                pageSize: 20,
                style: "width:100%;height:100%;"
            });

            // mini-buttonedit需要特殊处理
            grid.on('cellbeginedit', function(e) {
                var editor = e.column.editor;
                if (editor && editor.setText) {
                    editor.setText(e.record[e.field]);
                }
            });
        });
    };
    rs.printSetup = function() { // 打印格式设置
        var grid = [];
        var controls = rs.getByType("datagrid"); // 取datagrid组件列表数据定义
        controls = controls.concat(rs.getByType("treegrid")); //合并treegrid组件列表数据定义
        for (var index = 0; index < controls.length; index++) {
            var griditem = controls[index];
            if (griditem.tag && griditem.tag < 0)
                continue;
            var id = griditem.id;
            var info = [];
            var columns = griditem.columns;
            for (var i = 0; i < columns.length; i++) {
                var field = columns[i].field;
                if (!field || field == '') continue;
                var header = columns[i].header;
                var temp = {
                    "field": field,
                    "header": header
                };
                info.push(temp);
            }
            var data;
            if (griditem.type == 'datagrid') data = griditem.getData();
            else if (griditem.type == 'treegrid') {
                var data = griditem.getList();
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    if (item && item.children) delete item.children;
                }
            }
            grid.push({
                id: id,
                info: info,
                data: data
            });
        }
        var mkmc = sysinfo.gnmkinfo.name;
        this.open({
            url: "openmodule.do?id=PUB01", // 打印格式设置的URL
            title: "报表格式设置",
            width: "750",
            height: "400",
            onload: function() {
                var win = this.getIFrameEl().contentWindow;
                var data = {
                    "mkid": mkid,
                    "mkmc": mkmc,
                    "griddata": grid
                };
                win.onLoad(data);
            },
            ondestroy: function(action) {
                var win = this.getIFrameEl().contentWindow;
                var cfgdata = rs.clone(win.getData());
                var printmenu = rs.get("printMenu");
                var previewMenu = rs.get("previewMenu");
                if (cfgdata) { //重新生成打印及预览菜单项
                    printmenu.setItems([]);
                    previewMenu.setItems([]);
                    var printlist = [],
                        previewlist = [];
                    for (var i = 0; i < cfgdata.length; i++) {
                        var item = cfgdata[i];
                        if (item.zt == 'N' || !item.bbmc || !item.bbid) continue;
                        var printitem = new mini.MenuItem();
                        var previewitem = new mini.MenuItem();
                        printitem.setText(item.bbmc);
                        previewitem.setText(item.bbmc);
                        printitem.on("click", "rs.Report(1," + item.bbid + ")");
                        printlist.push(printitem);
                        previewitem.on("click", "rs.Report(2," + item.bbid + ")");
                        previewlist.push(previewitem);
                    }
                    printmenu.setItems(printlist);
                    previewMenu.setItems(previewlist);
                }
            }
        });
    };
    rs.checkkey = function(key) { //校验是否存在无关数据项，存在返回false，否则返回true
        var keylist = {};
        keylist.pageIndex = '';
        keylist.sortField = '';
        keylist.sortOrder = '';
        keylist.opttype = '';
        keylist.operid = '';
        keylist.opername = '';
        keylist.corpid = '';
        keylist._id = '';
        keylist._uid = '';
        return (keylist[key]) ? false : true;
    };
    rs.Report = function(type, bbid) { //报表打印函数，接收报表ID
        // 检测报表插件
        var rootWindow = rs.getRootWindow(window);
        if (!rootWindow.Report_Detect()) {
            return;
        }

        var grid = {};
        var selected = new Array();
        var controls = rs.getByType("datagrid");
        controls = controls.concat(rs.getByType("treegrid"));
        for (var index = 0; index < controls.length; index++) {
            var griditem = controls[index];
            if (griditem.tag && griditem.tag < 0)
                continue;
            var data;
            if (griditem.type == 'datagrid') {
                data = griditem.getData();
            }
            else if (griditem.type == 'treegrid') {
                var data = griditem.getList();
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    if (item && item.children) delete item.children;
                }
            }
            var id = griditem.id;
            grid[id] = data;
            var selectdata = rs.clone(griditem.getSelected());
            if (selectdata) {
                if (selectdata.pageIndex) delete selectdata.pageIndex;
                if (selectdata.pageSize) delete selectdata.pageSize;
                if (selectdata.sortField) delete selectdata.sortField;
                if (selectdata.sortOrder) delete selectdata.sortOrder;
                if (selectdata._id) delete selectdata._id; 
                if (selectdata._uid) delete selectdata._uid;
                if (selectdata.opttype) delete selectdata.opttype;
                if (selectdata.operid) delete selectdata.operid;
                if (selectdata.opername) delete selectdata.opername;
                if (selectdata.corpid) delete selectdata.corpid;
                if (selected.length == 0)
                    selected[0] = selectdata;
                else {
                    selected[1] = [];
                    for (var key in selectdata) {
                        if (!selected[1][key])
                            selected[1][key] = selectdata[key];
                    }
                }
            }
            if( controls.length > 1 && index !== 0) {
               for(var gridIndex = 0; gridIndex < grid[id].length; gridIndex++){
                  rs.ObjectAssign(grid[id][gridIndex], selected[0]);
                }
            }
        }
            
        /*  grid.Param = new Array();
            var Param = {};
            Param.userid = sysinfo.userinfo.id;
            Param.username = sysinfo.userinfo.name;
            Param.corpid = sysinfo.corpinfo.id;
            Param.corpname = sysinfo.corpinfo.name;
            Param.corpaddress = sysinfo.corpinfo.address;
            grid.Param[0] = Param;  */

        var param = {
            "opttype": 12,
            "mkid": mkid,
            "bbid": bbid
        };
        var url = bootPATH + "sys/BbpzProc.do";
        if (Report.Register == undefined) {
            alert("未安装报表插件或浏览器不支持报表打印，请检查!");
            return;
        }
        rs.post(url, param, function(result) {
            var rptstr = "";
            if (result.ret_code == '0000') {
                if (result.data && result.data.length > 0) Report.LoadFromStr(result.data);
                else {
                    alert("操作前请配置并保存报表打印模版!");
                    return;
                };
            } else {
                alert("装载报表模版数据发生错误，请检查模版配置!");
                return;
            };
            var rptdata = rs.encode(grid);
            Report.LoadDataFromXML(rptdata);
            if (type == 1) // 打印标识
                Report.Print(true);
            else if (type == 2) // 打印预览标识
                Report.PrintPreview(true);
        });
    };  
    
    rs.ObjectAssign = function(target){
    	    'use strict';
    	    if (target == null) {
    	      throw new TypeError('Cannot convert undefined or null to object');
    	    }

    	    target = Object(target);
    	    for (var index = 1; index < arguments.length; index++) {
    	      var source = arguments[index];
    	      if (source != null) {
    	        for (var key in source) {
    	          if (Object.prototype.hasOwnProperty.call(source, key)) {
                    if (!target.hasOwnProperty(key)) {
                        target[key] = source[key];
                    }
    	          }
    	        }
    	      }
    	    }
    	    return target;
    }
    
    rs.AllowReportSelect = function(allow){
    	rs.get("btnPreviewSelect").setVisible(allow);
    	rs.get("btnPrintSelect").setVisible(allow);
    	rs.get("btnPreview").setVisible(!allow);
    	rs.get("btnPrint").setVisible(!allow);
    }
    
    rs.ReportSelect = function(type, bbid) { //报表打印函数，接收报表ID
        // 检测报表插件
        var rootWindow = rs.getRootWindow(window);
        if (!rootWindow.Report_Detect()) {
            return;
        }

        var grid = {};
        grid.selected = new Array();
        var controls = rs.getByType("datagrid");
        controls = controls.concat(rs.getByType("treegrid"));
        for (var index = 0; index < controls.length; index++) {
            var griditem = controls[index];
            if (griditem.tag && griditem.tag < 0)
                continue;
            var data;
            if (griditem.type == 'datagrid') 
            	data = griditem.getSelecteds();
            else if (griditem.type == 'treegrid') {
                var data = griditem.getList();
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    if (item && item.children) delete item.children;
                }
            }
            var id = griditem.id;
            grid[id] = data;
            var selectdata = rs.clone(griditem.getSelected());
            if (selectdata) {
                if (selectdata.pageIndex) delete selectdata.pageIndex;
                if (selectdata.pageSize) delete selectdata.pageSize;
                if (selectdata.sortField) delete selectdata.sortField;
                if (selectdata.sortOrder) delete selectdata.sortOrder;
                if (selectdata._id) delete selectdata._id;
                if (selectdata._uid) delete selectdata._uid;
                if (selectdata.opttype) delete selectdata.opttype;
                if (selectdata.operid) delete selectdata.operid;
                if (selectdata.opername) delete selectdata.opername;
                if (selectdata.corpid) delete selectdata.corpid;
                if (grid.selected.length == 0)
                    grid.selected[0] = selectdata;
                else {
                    for (var key in selectdata) {
                        if (!grid.selected[0][key])
                            grid.selected[0][key] = selectdata[key];
                    }
                }
            }
        }
        var param = {
                "opttype": 12,
                "mkid": mkid,
                "bbid": bbid
            };
            var url = bootPATH + "sys/BbpzProc.do";
            if (Report.Register == undefined) {
                alert("未安装报表插件或浏览器不支持报表打印，请检查!");
                return;
            }
            rs.post(url, param, function(result) {
                var rptstr = "";
                if (result.ret_code == '0000') {
                    if (result.data && result.data.length > 0) Report.LoadFromStr(result.data);
                    else {
                        alert("操作前请配置并保存报表打印模版!");
                        return;
                    };
                } else {
                    alert("装载报表模版数据发生错误，请检查模版配置!");
                    return;
                };
                var rptdata = rs.encode(grid);
                Report.LoadDataFromXML(rptdata);
                if (type == 1) // 打印标识
                {
                    Report.Print(true);
                    SetDYBZ();
                }
                else if (type == 2) // 打印预览标识
                    Report.PrintPreview(true);
            });
        };
    
    /*  获取当前界面有效的数据列表  */
    rs.getByType = function(type) {
        var controls = mini.findControls(function(obj) {
            if (type == "datagrid" || type == "treegrid")
                return (obj.type == type && obj.columns && obj.columns.length >= 4) ? true : false;
            else if (obj.type == type) return true;
        });
        return controls;
    };
    /* 获取功能模块查询条件输入区的变量信息  */
    rs.getQryParam = function() {
        var varparam = [];
        varparam.push({
            "id": "qryparam",
            "varid": '查询条件变量'
        });
        var qryParam = $("div[id='pnlsearch'] form td input");
        for (var i = 0; i < qryParam.length; i++) {
            try {
                var obj = qryParam[i];
                if (!obj.id) continue;
                var id = obj.id;
                var index = id.indexOf("$text");
                if (index < 0) continue;
                id = id.substring(0, index);
                var label = $("#label" + id).text();
                if (label != "") {
                    index = label.indexOf(":") + label.indexOf("：") + 1;
                    if (index > 0) label = label.substring(0, index);
                    var temp = {
                        "id": id, //唯一标识
                        "varid": id, //变量名
                        "varname": label, //变量描述
                        "pid": "qryparam" //上级节点
                    };
                    varparam.push(temp);
                }
            } catch (e) {
                console.log(e);
            }
        }
        return varparam;
    };
    /*  获取功能数据列表变量信息   */
    rs.getGridParam = function() {
        var vardata = [];
        var controls = rs.getByType("datagrid");
        for (var i = 0; i < controls.length; i++) {
            var obj = controls[i];
            if (obj.tag && obj.tag < 0)
                continue;
            var id = obj.id;
            var name = obj.name;
            var columns = rs.get(id).columns;
            var text = (name) ? name : id;
            vardata.push({
                "id": id,
                "varid": "数据集变量：" + text
            });
            for (var j = 0; j < columns.length; j++) { // 获取主页面列表的列集合
                var name = columns[j].name;
                if (name == undefined || name == '') continue;
                var temp = {
                    "id": name,
                    "varid": columns[j].field, //变量名称
                    "varname": columns[j].header, //变量描述
                    "pid": id //上级节点
                };
                vardata.push(temp);
            }
        }
        return vardata;
    };
    /* 获取功能模块变量信息 */
    rs.getMkParam = function() {
        var vardata = rs.getQryParam(); // 查询区变量的集合
        var griddata = rs.getGridParam();
        vardata = vardata.concat(griddata);
        return vardata;
    };
    /* 参数说明：dataGrid:主页面列表 */
    rs.showVarInfo = function() {
        var vardata = rs.getMkParam();
        mini.open({
            url: 'public/gnbl.html',
            title: "当前功能可用变量",
            width: "500",
            height: "400",
            onload: function() {
                var win = this.getIFrameEl().contentWindow;
                win.setData(vardata);
            }
        });
    };
    //参数说明： 查看功能模块信息
    rs.showMkInfo = function() {
        var gnmkinfo = sysinfo.gnmkinfo;
        var mkinfo = [];
        mkinfo.push({ id: "base", info: "基本信息", desc: "" });
        mkinfo.push({ id: "base01", info: "模块编码", value: gnmkinfo.mkid, pid: "base" });
        mkinfo.push({ id: "base02", info: "模块名称", value: gnmkinfo.name, pid: "base" });
        mkinfo.push({ id: "base03", info: "模块版本", value: gnmkinfo.version, pid: "base" });
        mkinfo.push({ id: "base04", info: "打印格式模版", value: gnmkinfo.reptfile, pid: "base" });
        mkinfo.push({ id: "base05", info: "帮助文件", value: gnmkinfo.hlpfile, pid: "base" });
        mkinfo.push({ id: "run", info: "运行参数", value: "" });
        if (gnmkinfo.varinfo && gnmkinfo.varinfo.length > 0) {
            var varinfo = rs.decode(gnmkinfo.varinfo);
            for (var i = 0; i < varinfo.length; i++) {
                var item = varinfo[i];
                mkinfo.push({ id: "run" + i, info: item.id, value: item.name, pid: "run" });
            }
        }
        mini.open({
            url: 'public/ckmkinfo.html',
            title: "查看模块信息",
            width: "500",
            height: "400",
            onload: function() {
                var win = this.getIFrameEl().contentWindow;
                win.setData(mkinfo);
            }
        });
    };
    //业务单据文档管理     bAddBtn, bDelBtn, bEditBtn, bDownBtn分别控制添加，删除，上传，下载按钮大权限 
    rs.FileMgr = function(mlid, fjz, bAddBtn, bDelBtn, bEditBtn, bDownBtn) {
        if (!mlid || mlid.length == 0 || !fjz || fjz.length == 0) {
            rs.showMessageBoxError("文档目录编码及附件组编码不能为空，请确认!");
            return;
        }
        bAddBtn = (bAddBtn !== undefined) ? bAddBtn : true;
        bDelBtn = (bDelBtn !== undefined) ? bDelBtn : true;
        bEditBtn = (bEditBtn !== undefined) ? bEditBtn : true;
        bDownBtn = (bDownBtn !== undefined) ? bDownBtn : true;
        var url = "wdgl/WdmlProc.do";
        var param = {};
        param.mkid = mkid;
        param.opttype = Constants.OPT_QUERY;
        param.wdlx = "2"; //文档类型为单据附件
        param.mlid = mlid;
        rs.post(url, param, function(result) {
            if (result.ret_code == "0000") {
                if (result.data && result.data.length > 0) {
                    var data = {};
                    data.mlid = mlid;
                    data.fjz = fjz;
                    data.mlinfo = result.data[0];
                    data.bAdd = bAddBtn;
                    data.bDel = bDelBtn;
                    data.bEdit = bEditBtn;
                    data.bDown = bDownBtn;
                    mini.open({
                        url: "openmodule.do?id=PUB04",
                        title: "文档管理",
                        width: "850",
                        height: "500",
                        onload: function() {
                            var win = this.getIFrameEl().contentWindow;
                            win.onLoad(data);
                        }
                    });
                } else
                    rs.showtips("警告", "编码【" + mlid + "】的文档目录不存在，请检查!", "warning", 3000);
            } else rs.showMessageBoxError("查询文档目录编码【" + mlid + "】失败，" + (ret.ret_desc || "请检查重试"));
        });
    };
    
    //业务单据文档管理
    rs.SendFile = function(mlid, fjz, fbsm, gyslist, fbid) {
        if (!mlid || mlid.length == 0 || !fjz || fjz.length == 0) {
            rs.showMessageBoxError("文档目录编码及附件组编码不能为空，请确认!");
            return;
        }
        if (!gyslist || gyslist.length == 0) {
            rs.showMessageBoxError("供应商编码不能为空，请确认!");
            return;
        }
        var url = "wdgl/sendFile.do";
        var param = {};
        param.mkid = mkid;
        param.opttype = Constants.OPT_SENDFILE;
        param.wdlx = "2"; //文档类型为单据附件
        param.wdml = mlid;
        param.fbsm = fbsm;
        param.fjz = fjz;
        param.gyslist = gyslist;
        param.fbid = fbid;
        rs.post(url, param, function(result) {
            if (result.ret_code == "0000") {
            	rs.showTipsSuccess("文件发送成功");
            } else rs.showMessageBoxError("文件发送失败，" + (result.ret_desc || "请检查重试"));
        });
    };
    
    rs.showList = function() {
        var split = mini.get('mainSplit');
        split.hidePane(0);
    };
    rs.listSchema = function() { // 列表权限方案设置
        var grid = {};
        var controls = rs.getByType("datagrid");
        for (var index = 0; index < controls.length; index++) {
            var griditem = controls[index];
            if (griditem.tag && griditem.tag < -1)
                continue;
            var id = griditem.id;
            var info = {
                name: griditem.name,
                data: []
            };
            var columns = griditem.columns;
            for (var i = 0; i < columns.length; i++) {
                var field = columns[i].field;
                if (!field || field == '') continue;
                var temp = {
                    "field": field,
                    "name": columns[i].name,
                    "header": columns[i].header
                };
                info.data.push(temp);
            }
            grid[id] = info;
        }
        mini.open({
            url: "openmodule.do?id=PUB02",
            // 设置列表权限方案的URL
            title: "列表权限方案设置",
            width: "600",
            height: "500",
            onload: function() {
                var win = this.getIFrameEl().contentWindow;
                var data = {
                    "mkid": mkid,
                    "griddata": grid
                };
                win.onLoad(data);
            },
            ondestroy: function(action) { //方案设置结束，应用列表设置
                rs.setGridList();
            }
        });
    };
    rs.listSetup = function() { // 列表栏目方案设置
        var grid = {};
        var controls = rs.getByType("datagrid");
        for (var index = 0; index < controls.length; index++) {
            var griditem = controls[index];
            if (griditem.tag && griditem.tag < -1) //增加对不作为变量输出的数据列表进行控制
                continue;
            var id = griditem.id;
            var info = {
                name: griditem.name,
                data: []
            };
            var sortField = griditem.sortField;
            var sortorder = griditem.sortOrder;
            var columns = griditem.columns;
            for (var i = 0; i < columns.length; i++) {
                var field = columns[i].field;
                if (!field || field == '') continue;
                var temp = {
                    "field": field,
                    "name": columns[i].name,
                    "header": columns[i].header,
                    "width": columns[i].width,
                    "visible": columns[i].visible ? 'Y' : 'N',
                    "summarytype": columns[i].summaryType,
                    "allowsort": columns[i].allowSort,
                    "sortorder": ""
                };
                if (field == sortField) temp.sortorder = sortorder;
                info.data.push(temp);
            }
            grid[id] = info;
        }
        mini.open({
            url: "openmodule.do?id=PUB03", // 设置列表栏目方案的URL
            title: "列表栏目设置",
            width: "700",
            height: "550",
            onload: function() {
                var win = this.getIFrameEl().contentWindow;
                var data = {
                    "mkid": mkid,
                    "griddata": grid
                };
                win.onLoad(data);
            },
            ondestroy: function(action) { //方案设置结束，应用列表设置
                rs.setGridList();
            }
        });
    };
    rs.setGridList = function() {
        var url = bootPATH + "sys/GridProc.do";
        var listSchema = function(result) { //列表权限方案处理函数
            if (result.ret_code == "0000") {
                var data = result.data;
                if (data == undefined) return; // 如果没有列表权限方案配置，则直接退出
                var listset = {};
                for (var i = 0; i < data.length; i++) {
                    var listid = data[i].listid;
                    listset[listid] = data[i]; //指定功能列表栏目方案信息
                }
                for (var key in listset) {
                    var listid = key;
                    var gridset = rs.decode(listset[key].data); // item.data
                    var grid = rs.get(listid);
                    var columns = grid.columns;
                    gridset.forEach(function(set) { //列表权限方案如果不显示
                        if (set.visible == 'N') grid.hideColumn(set.name);
                        else grid.showColumn(set.name);
                    });
                }
            }
        };
        var listGrid = function(result) {
            if (result.ret_code == "0000") {
                var data = result.data;
                if (data == undefined) return; // 如果没有列表栏目方案配置，则直接退出
                var listset = {};
                for (var i = 0; i < data.length; i++) {
                    var listid = data[i].listid;
                    var value = listset[listid];
                    if (value) {
                        if (value.gy == "N") // 个人设置
                            continue;
                        else listset[listid] = data[i]; //指定功能列表栏目方案信息
                    } else listset[listid] = data[i];
                }
                for (var key in listset) {
                    var listid = key;
                    var gridset = rs.decode(listset[key].data); // item.data
                    var grid = rs.get(listid);
                    grid.set({
                        showSummaryRow: false
                    });
                    grid.set({
                        showFilterRow: false
                    });
                    var columns = grid.columns;
                    var gridmap = {};
                    columns.forEach(function(col) {
                        //    grid.hideColumn(col.name);
                        gridmap[col.field] = col;
                    });
                    var colsmap = {};
                    gridset.forEach(function(set) {
                        var col = gridmap[set.field];
                        col.header = set.header; // 设置列标题
                        if (set.visible == 'Y') // 设置列是否隐藏
                            grid.showColumn(set.name);
                        else grid.hideColumn(set.name);
                        col.allowSort = set.allowsort; // 设置列是否支持排序
                        col.width = set.width; // 设置列宽度
                        if (set.summarytype && set.summarytype != '') {
                            if (grid.showSummaryRow == false) {
                                grid.set({
                                    showSummaryRow: true
                                });
                                grid.on("drawsummarycell", rs.onDrawsummarycell);
                            }
                            col.summaryType = set.summarytype;
                        }
                        if (set.filter && set.filter != '') {
                            if (grid.showFilterRow == false) grid.set({
                                showFilterRow: true
                            });
                        }
                        if (set.allowsort) {
                            if (grid.sortMode == undefined) grid.set({
                                sortMode: "client"
                            });
                        }
                        if (set.sortorder && set.sortorder != '') {
                            col.sortField = set.field;
                            col.sortOrder = set.sortorder;
                            grid.sortBy(set.field, set.sortorder);
                        }
                        colsmap[col.name] = col;
                    });
                    //-------------------取出数据列差异-------------------//
                    var colsdiff = [];
                    columns.forEach(function(item) {
                        var value = colsmap[item.name];
                        if (value == undefined) colsdiff.push(item);
                    });
                    var cols = [];
                    for (var key in colsmap) {
                        cols.push(colsmap[key]);
                    }
                    //--------------------------------------------------//
                    cols = cols.concat(colsdiff);
                    grid.setColumns(cols); //合并两个数据列数组，并将新数据列数组赋给数据列表
                }
            }
        };
        //如当前用户具有列表权限方案设置权限，则不处理列表初始化设置
        var lbqx = rs.getParamById("LBQX001"); //LBQX001为用户列表权限方案参数
        if (!lbqx || lbqx == 'Y') return;
        //-------------------------------------------------------
        $.ajaxSetup({
            async: false
        });
        try {
            //------------------------------列表权限方案设置开始-------------------------//
            var param = {
                opttype: 10,
                mkid: mkid
            }; //查询列表权限方案配置信息
            rs.post(url, param, listSchema);
            //------------------------------列表权限方案设置结束-------------------------//
            //------------------------------列表栏目方案设置开始-------------------------//
            param = {
                opttype: Constants.OPT_QUERY,
                mkid: mkid,
                qs: 'Y',
                gy: "Y"
            };
            rs.post(url, param, listGrid); //列表栏目方案设置开始
        } finally {
            $.ajaxSetup({
                async: false
            });
        }
    };
    //datagrid渲染汇总数据行时调用
    rs.onDrawsummarycell = function(e) {
        var smtype = e.column.summaryType;
        var fmt = "<span style='color:blue; text-align:center; display:block;'>{0}</span>";
        if (smtype && smtype != '') {
            if (smtype == 'sum') {
                var str = "合计：" + e.cellHtml;
                e.cellHtml = fmt.format(str);
            } else if (smtype == 'avg') {
                var str = "平均：" + e.cellHtml;
                e.cellHtml = fmt.format(str);
            } else if (smtype == 'min') {
                var str = "最小值：" + e.value + " 条";
                e.cellHtml = fmt.format(str);
            } else if (smtype == 'max') {
                var str = "最大值：" + e.value;
                e.cellHtml = fmt.format(str);
            } else if (smtype == 'count') {
                var str = "记录数：" + e.value + " 条";
                e.cellHtml = fmt.format(str);
            }
        }
    };
    //相关功能设置处理
    rs.FunSetup = function() {
        var vardata = rs.getGridParam();
        var data = {
            mkid: mkid,
            param: vardata
        };
        mini.open({
            url: "public/funcfg.html",
            title: "相关功能配置",
            showModal: true,
            allowResize: false,
            width: 830,
            height: 540,
            onload: function() {
                var win = this.getIFrameEl().contentWindow;
                win.onLoad(data);
            },
            ondestroy: function(action) { //动态创建相关功能菜单项
                var win = this.getIFrameEl().contentWindow;
                var cfgdata = rs.clone(win.getFunData()); //回调获取最新相关功能配置
                if (cfgdata) {
                    var menulist = rs.get("funMenu");
                    if (menulist) menulist.setItems([]);
                    var itemlist = [];
                    cfgdata.forEach(function(item) {
                        var menuitem = new mini.MenuItem(); //动态创建相关功能菜单项
                        menuitem.setText(item.mkname);
                        menuitem.on("click", "rs.FunProc('" + item.glmkid + "','" + item.mkname + "','" + item.glparam + "')");
                        itemlist.push(menuitem);
                    });
                    menulist.setItems(itemlist);
                }
            }
        });
    };
    //相关功能处理函数,接收关联的功能ID，功能名称、关联的功能参数
    rs.FunProc = function(glmkid, mkname, glparam) {
        var param = [];
        if (glparam && glparam.length > 0) {
            var paramobj = rs.decode(glparam);
            for (var i = 0; i < paramobj.length; i++) {
                var item = paramobj[i];
                var gridparam = item.param.split(":");
                if (!gridparam || gridparam.length < 2) continue;
                //如果关联参数不存在或参数不符合格式，则跳过该参数处理
                var gridid = gridparam[0];
                var field = gridparam[1];
                var grid = rs.get(gridid);
                if (!grid) continue;
                var data;
                if (grid.type == 'datagrid') //如果数据列表为datagrid类型，则取数据用getData()方法
                    data = grid.getData();
                else if (grid.type == 'treegrid') //如果数据列表为treegrid类型，则取数据用getList()方法
                    data = grid.getList();
                if (!data || data.length == 0) //如果数据列表为空，则跳过当前参数
                    continue;
                var row = grid.getSelected();
                if (!row) continue; //如果指定列表未选中一条记录，则跳过该取值参数
                var value = row[field];
                if (!value) continue; //如果取不到指定列表数据的参数值 ，则跳过该取值参数
                param.push({
                    id: item.id,
                    value: value
                }); //将设置无素ID及参数值传给数组列表
            }
        }
        var node = {
            mkid: glmkid,
            name: mkname
        };
        var paramjson = rs.encode(param);
        paramjson = encodeURIComponent(paramjson);
        parent.showTab(node, paramjson);
    };
    //辅助输入处理函数
    rs.fzsrProc = function(e) {
        var userid = sysinfo.userinfo.id; /* 获取登录用户编码 */
        if (!userid) userid = "";
        var value = "";
        var obj = e.sender;
        var objtype = obj.type;
        if (objtype == "textbox") value = obj.getInputText();
        else if (objtype == "buttonedit") value = obj.getValue();
        var inputid = obj.id;
        var label = $('#label' + inputid).text();
        if (label && label.length > 0) {
            var index = label.indexOf(":") + label.indexOf("：") + 1;
            if (index > 0) label = label.substring(0, index);
        } else label = "";
        if (label == "" && obj.desc) label = obj.desc;
        mkid = (mkid) ? mkid : "0000";
        inputid = mkid + '-' + inputid;
        var param = {
            fzsrid: inputid,
            opttype: 10,
            mkid: mkid
        };
        /* 查询辅助输入码信息 */
        rs.post(bootPATH + "sys/FzsrProc.do", param, function(result) {
            var ret_code = result.ret_code;
            if (ret_code == '0000' || ret_code == '0001' || ret_code == '0002') {
                var type = (ret_code == '0001') ? 2 : 1;
                var openurl = "",
                    data = {};
                /* 定义打开的url地址及传入的数据 */
                if (ret_code == '0000' || ret_code == '0001') { //0000:辅助输入SQL配置  0001:自定义数据项
                    openurl = bootPATH + '/public/dlgfzsr.html';
                    data = {
                        "id": inputid,
                        "value": value,
                        "type": type,
                        "userinfo": sysinfo.userinfo,
                        "data": result.data
                    };
                } else if (ret_code == '0002') { //0002:打开信息模块
                    openurl = bootPATH + '/openmodule.do?id=' + result.data.mkcode;
                    data = {
                        "id": inputid,
                        "value": value,
                        "mkid": mkid,
                        "userinfo": sysinfo.userinfo
                    };
                }
                rs.open({
                    title: '辅助输入[' + label + "]",
                    url: openurl,
                    showModal: false,
                    allowResize: false,
                    width: 700,
                    height: 550,
                    onload: function() {
                        var win = this.getIFrameEl().contentWindow;
                        win.onLoad(data);
                    },
                    ondestroy: function(action) {
                        if (action == 'ok') {
                            var win = this.getIFrameEl().contentWindow;
                            var result = win.getData();
                            if (objtype == "textbox") obj.setValue(result);
                            else if (objtype == "buttonedit") {
                                obj.setValue(result);
                                obj.setText(result);
                            }
                            obj.focus();
                        }
                    }
                });
            } else {
                rs.alert("辅助输入出现错误，请联系平台客服人员！");
                return;
            }
        });
    };
    rs.getParam = function(url, param) { // 取初始化、系统、用户参数公共调用函数
        var result;
        try {
            $.ajaxSetup({
                async: false
            });
            this.post(url, param, function(data) {
                result = (data.ret_code == '0000') ? data.data : "";
            });
            return result;
        } finally {
            $.ajaxSetup({
                async: true
            });
        }
    };
    rs.getParamById = function(csid) { // 根据参数ID获取参数值
        var param = {
            opttype: 8,
            csid: csid
        }; // 操作编码 按参数ID查询参数值
        return this.getParam("sys/ParamProc.do", param);
    };
    rs.getParamByMkid = function(mkid) { // 根据功能模块编码查询参数配置
        var param = {
            opttype: 9,
            mkid: mkid
        }; // 操作编码 按参数ID查询参数值
        return this.getParam("sys/ParamProc.do", param);
    };
    rs.closeTab = function() { // 在功能页面中关闭当前功能所在标签页
        if (window.parent.onCloseTab)
            window.parent.onCloseTab();
        else {
            window.open('', '_parent', '');
            window.close();
        }
    };
    rs.CloseWin = function(winid) { // 关闭页面子窗口
        mini.get(winid).hide();
    };
    rs.alert = function(msg, title, callback) { // 弹出提示
        return mini.alert(msg, title, callback);
    };
    rs.confirm = function(msg, title, callback) { // 弹出确认提示
        return mini.confirm(msg, title, callback);
    };
    rs.loading = function(msg, title) { // 显示加载中提示
        return mini.loading(msg, title);
    };
    rs.DataBinding = mini.DataBinding; // 将dbgrid与表单进行数据绑定
    rs.showtips = function(title, msg, state, timeout) { // 显示自动提示
        var param = {
            content: "<b>" + title + "</b><br/>" + msg,
            state: state,
            x: 'center',
            y: 'center',
            timeout: timeout || 3000
        };
        mini.showTips(param);
    };
    rs.showTipsSuccess = function(message) {
        message = message || '操作成功';
        mini.showTips({
            content: "<b>成功</b><br/>" + message,
            state: 'success',
            x: 'center',
            y: 'center'
        });
    };
    rs.showTipsInfo = function(message) {
        message = message || '操作成功';
        mini.showTips({
            content: "<b>提示</b><br/>" + message,
            state: 'info',
            x: 'center',
            y: 'center'
        });
    };
    rs.showMessageBoxError = function(message, title) {
        message = message || '操作失败，请检查重试';
        title = title || '错误';
        mini.showMessageBox({
            title: title,
            message: message,
            buttons: ["ok"],
            iconCls: "mini-messagebox-error"
        });
    };
    rs.setItem = function(name, value) {
        localStorage.setItem(name, value);
    };
    rs.getItem = function(name) {
        return localStorage.getItem(name);
    };
    rs.removeItem = function(name) {
        localStorage.removeItem(name);
    };
    rs.checkParamExistInSql = function(sql) {
        if (undefined === sql) {
            return false;
        }
        return /#{\s*\w+\s*}/.test(sql);
    };
    rs.encode = function(obj) { // 将JS对象编码成JSON格式
        return mini.encode(obj);
    };
    rs.decode = function(json, autoParseDate) { // 将JSON格式字符串解码成JS对象
        return mini.decode(json, autoParseDate);
    };
    rs.layout = function() { // 对界面重新布局
        mini.layout();
    };
    rs.form = function(id) { // 创建Form表单对象
        return new mini.Form(id);
    };
    rs.get = function(id) { // 根据ID获取mini UI对象
        return mini.get(id);
    };
    // 显示控件
    rs.show = function(id) {
        if (mini.get(id)) {
            mini.get(id).show();
        }
    };
    // 隐藏控件
    rs.hide = function(id) {
        if (mini.get(id)) {
            mini.get(id).hide();
        }
    };
    // 显示/隐藏控件
    rs.toggle = function(id) {
        var controller = mini.get(id);
        if (controller) {
            if (controller.visible) {
                rs.hide(id);
            } else {
                rs.show(id);
            }
        }
    };
    rs.openwin = function(url, title, options) { // 打开一个windows窗口
        window.open(url, title, options);
    };
    rs.open = function(options) { // 打开一个页外窗口
        mini.open(options);
    };
    rs.openfunc = function(node, param) { // 打开另外一个功能
        window.parent.showTab(node, param);
    };
    rs.openmk = function(mkid, param) { // 打开模块显示在标签栏
        var rootWindow = this.getRootWindow(window);
        var gTreeMenu = rootWindow.gTreeMenu;
        var node = gTreeMenu.getNode(mkid);
        if (null !== node) {
            rootWindow.showTab(node, param);
        }
    };
    rs.getRootWindow = function(w) {
        var rootWindow = w.parent;
        while (rootWindow && rootWindow !== rootWindow.parent) {
            rootWindow = rootWindow.parent;
        }
        return rootWindow;
    };
    rs.isExistsFunc = function(funcName) { // 是否存在指定函数
        try {
            return (typeof(eval(funcName)) == "function") ? true : false;
        } catch (e) {
            console.log(e);
        }
        return false;
    };
    rs.isExistsVar = function(varName) { // 是否存在指定变量
        try {
            return (typeof(variableName) == "undefined") ? false : true;
        } catch (e) {
            console.log(e);
        }
        return false;
    };
    rs.ajax = function(obj) { // 二次封装ajax函数
        this.fail = function(data) {
            rs.alert("网络错误，请稍候重试!", "提示");
        };
        var url = obj.url,
            data = obj.data,
            method = obj.method || "POST",
            success = obj.success,
            fail = obj.fail || this.fail;
        var type = obj.type || "application/x-www-form-urlencoded;charset=UTF-8";
        return $.ajax({
            url: url,
            contentType: type,
            data: data,
            type: method,
        }).done(success).fail(fail);
    };
    rs.getJSON = function(url, data, success) {
        return $.getJSON(url, data, success).fail(function() {
            rs.alert("网络错误，请稍候重试!", "提示");
        });
    };
    rs.post = function(url, data, success, type) { // 二次封装ajax的post函数
        return rs.ajax({
            "url": url,
            "data": data,
            "type": type,
            "success": success
        });
    };
    /**
     * ajax请求，默认方法为post，发送数据为json格式
     *
     * @param settings
     *            ajax设置
     */
    rs.postJson = function(settings) {
        if (settings === void 0) {
            return jQuery.post({
                contentType: 'application/json; charset=UTF-8'
            });
        }
        settings.method = 'POST';
        settings.contentType = 'application/json; charset=UTF-8';
        if (settings.data) {
            settings.data = JSON.stringify(settings.data);
        }
        return jQuery.ajax(settings);
    };
    rs.clone = function(obj) { // 克隆一个JS对象数据并返回
        return mini.clone(obj);
    };
    /*
     * 前端功能初始化、功能参数设置、栏目列表设置 参数: mkid: 功能模块编码 version: 功能模块版本 param: 需初始化查询区的参数值
     */
    rs.initModule = function(version, param) {
        var gnmk = sysinfo.gnmkinfo; // 获取功能模块信息
        var init = {
            setSearchValue: function(paramvalue) { // 根据外部传入的参数值初始化查询输入区的值
                if (paramvalue && paramvalue.length > 0) {
                    try {
                        var json = rs.decode(paramvalue);
                        if (json) {
                            json.forEach(function(item) {
                                rs.get(item.id).setValue(item.value);
                            });
                        };
                    } catch (e) {
                        console.log(e);
                    };
                };
            },
            showHelp: function(title, hlp, option) { // 显示功能的帮助信息
                if (!hlp || hlp.length == 0) {
                    rs.showtips("提示", "帮助文件正在编写中...", "warning");
                    return;
                }
                window.open(hlp, title + "帮助", "height=768,width=1024,top=10,left=10,toolbar=no,menubar=no," + "scrollbars=yes,resizable=yes,location=no,status=yes");
            },
            getRunParam: function() { //获取功能查询条件区的变量信息
                var param = [];
                var runparam = $("div[id='pnlsearch'] form td input");
                for (var i = 0; i < runparam.length; i++) {
                    try {
                        var obj = runparam[i];
                        if (!obj.id) continue;
                        var id = obj.id;
                        var index = id.indexOf("$text");
                        if (index < 0) continue;
                        id = id.substring(0, index);
                        var label = $("#label" + id).text();
                        if (label != "") {
                            index = label.indexOf(":") + label.indexOf("：") + 1;
                            if (index > 0) label = label.substring(0, index);
                            var temp = {
                                "id": id,
                                "name": label
                            };
                            param.push(temp);
                        }
                    } catch (e) {
                        console.log(e);
                    }
                }
                return param;
            },
            initMKData: function() {
                /* 初始化功能模块查询区数据设置 */
                var mkinfo = {};
                mkinfo.ver = version; // 取initModule 函数的版本参数
                mkinfo.mkid = gnmk.mkid;
                if (version != gnmk.version) {
                    mkinfo.varinfo = rs.encode(init.getRunParam());
                    rs.post("initmk.do", mkinfo, function(result) {
                        if (result.ret_code != '0000') console.log(result.ret_desc);
                    });
                }
            },
            sethlpEvent: function() {
                /* 点击帮助初始化设置 */
                var title = gnmk.name;
                var hlpfile = gnmk.hlpfile;
                var btnhelp = mini.get('btnHelp');
                if (btnhelp != undefined) {
                    btnhelp.on("click", function(e) {
                        init.showHelp(title, hlpfile);
                    });
                }
                var helpmenu = mini.get('helpmenu');
                if (helpmenu != undefined) {
                    helpmenu.on("click", function(e) {
                        init.showHelp(title, hlpfile);
                    });
                }
            },
            // 处理当查询区设置showCollapseButton=true collapseOnTitleClick=true属性时，
            // 点击缩放时对界面进行重新部局处理
            setClickablePanel: function() {
                this.setPanelReLayout('pnlsearch');
                this.setPanelReLayout('panelDetail');
            },
            setPanelReLayout: function (panelId) {
                var panel = rs.get(panelId);
                if (panel != undefined) {
                    $(document).on('click', '.mini-panel-header', function(e) { // 点击查询区标题栏进行收缩时对界面重新进行部局
                        var panel = $(this).closest('.mini-panel-titleclick');
                        if (panel[0] && panel[0].id == panelId) setTimeout("rs.layout()", 10);
                    });
                    panel.on("buttonclick", function(e) { // 点击查询区右上角收缩按钮时对界面重新进行部局
                        if (e.name == "collapse") setTimeout("rs.layout()", 10);
                    });
                }
            },
            setFzsr: function() { /* F1辅助输入设置 */
                var controls = rs.getByType("textbox");
                controls.forEach(function(obj) {
                    obj.on("keydown", function(e) {
                        var keycode = e.htmlEvent.keyCode;
                        if (keycode == 112) /* 如果按键值为F2的话，则弹出辅助输入框 */
                            rs.fzsrProc(e);
                    });
                });
            },
            setGncz: function() { /*根据功能参数初始化默认的功能操作*/
                var csidmap = { "GNCS01": "btnAdd", "GNCS02": "btnRemove", "GNCS03": "btnEdit", "GNCS04": "btnPreview", "GNCS05": "btnPrint" };
                //设置新增、删除、修改、预览、打印五个基本功能操作编码与按钮编码
                if (sysinfo.gncsinfo) {
                    var gncs = sysinfo.gncsinfo;
                    if (!gncs.length || gncs.length == 0) return;
                    gncs.forEach(function(item) {
                        var csinfo = csidmap[item.CSID];
                        if (csinfo && item.VALUE == 'N')
                            rs.get(csinfo).disable();
                    });
                }
            }
        };
        // ---------------------------设置页面右键菜单-------------------------//
        $(function() {
            $(document).bind("contextmenu", function(e) {
                var menu = mini.get("pubmenu");
                if (menu != undefined) menu.showAtPos(e.pageX, e.pageY);
                return false;
            });
            init.initMKData(); // 初始化模块数据信息
            init.sethlpEvent(); // 设置公共按钮初始化事件
            init.setSearchValue(param); // 取initModule函数中的param参数值，并设置查询条件区的值
            init.setFzsr(); // 对所有mini-textbox输入框设置F1辅助输入
            init.setClickablePanel(); // 设置查询面板区的点击收缩事件
            init.setGncz(); // 根据功能参数设置初始化功能操作按钮
            rs.setGridList(); // 初始化列表栏目配置
            rs.setGridStyle(); // 对界面中所有的datagrid进行初始化
            if (window.onQuery) window.onQuery(); // 如果界面存在查询处理函数，则默认执行
        });
        // -------------------------------------------------
    };
    // 检测主Grid是否选中记录，若有则返回选中记录
    rs.checkMasterGridSelected = function() {
        var grid = window.getMasterGrid();
        if (grid) {
            var record = grid.getSelected();
            if (!record) {
                rs.alert('请先选择一条数据,再执行此操作！');
                return null;
            }
            return record;
        }
    };
    // 工作流操作函数工厂
    function bpmOptFactory(optCode, title, width, height) {
        return function() {
            var record = rs.checkMasterGridSelected();
            if (record) {
                var rootWindow = rs.getRootWindow(window);
                rootWindow.moduleWindow = window;
                rootWindow.bpmWindow = mini.open({
                    url: './wf/task.do?refMkid=' + window.wfid + '&wfInstNum=' + record.wfInstNum + '&optCode=' + optCode + '&basePath=' + bootPATH,
                    title: title || '提交工作流',
                    width: width || 900,
                    height: height || 650
                });
            }
        }
    };
    // 提交工作流
    rs.bpmCommit = bpmOptFactory('C', '提交工作流');
    // 退回工作流
    rs.bpmBack = bpmOptFactory('RJ', '退回工作流');
    // 撤回工作流
    rs.bpmRevoke = bpmOptFactory('RC', '撤回工作流', null, 580);
    // 我来处理
    rs.bpmHandle = bpmOptFactory('LMD', '我来处理');
    // 流程转交
    rs.bpmForward = bpmOptFactory('F', '流程转交');
    // 查看历史
    rs.bpmTrack = bpmOptFactory('TK', '查看历史');
    // 辅助函数：数组转对象
    rs.arrayToObject = function(array, fieldKey, fieldValue) {
        if (Array.isArray(array) && array.length > 0) {
            var object = {};
            array.forEach(function(item) {
                object[item[fieldKey]] = item[fieldValue];
            });
            return object;
        }
        return array;
    };
    return rs;
})(window.rs || {});
